from flask import Flask, render_template, request, redirect, url_for
import pymysql
import datetime

app = Flask(__name__, template_folder='')

# 数据库配置
db_config = {
    'host': 'localhost',
    'user': 'root',
    'password': '123456',
    'database': 'zhanghuimei',
    'charset': 'utf8mb4',
    'cursorclass': pymysql.cursors.DictCursor
}


# 连接数据库
def connect_db():
    return pymysql.connect(**db_config)


# 添加日记条目
@app.route('/add_entry', methods=['POST'])
def add_entry():
    date = datetime.datetime.now().date()
    weather = request.form['weather']
    mood = request.form['mood']
    events = request.form['events']

    try:
        connection = connect_db()
        with connection.cursor() as cursor:
            sql = "INSERT INTO `diary_entries` (`date`, `weather`, `mood`, `events`) VALUES (%s, %s, %s, %s)"
            cursor.execute(sql, (date, weather, mood, events))
            connection.commit()
        return redirect(url_for('history'))
    finally:
        connection.close()


# 显示历史记录
@app.route('/history')
def history():
    try:
        connection = connect_db()
        with connection.cursor() as cursor:
            sql = "SELECT * FROM `diary_entries` ORDER BY `date` DESC"
            cursor.execute(sql)
            entries = cursor.fetchall()
        return render_template('history.html', entries=entries)
    finally:
        connection.close()


# 主页（表单提交）
@app.route('/', methods=['GET', 'POST'])
def index():
    return render_template('index.html')


if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)
